﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using com.lib.events;
namespace com.lib.manager
{
    /// <summary>
    /// XML 管理并且缓存
    /// </summary>
   public class XMLManager
    {
       /// <summary>
       /// XML 缓存管理
       /// </summary>
       private static Dictionary<string, XmlDocument> data = new Dictionary<string, XmlDocument>();


       /// <summary>
       /// 读取XML.2种方式
       /// </summary>
       /// <param name="floder"></param>
       /// <param name="type"></param>
       public static void LoadXML(string floder,XMLType type = XMLType.Folder)
       {
           switch (type)
           {
               case XMLType.Folder:

                   LoadFromFolder(floder);

                   break;
               case XMLType.File:

                   LoadFromFile(floder);

                   break;
           }


       }
       private static void LoadFromFile(string floder)
       {
           IThreadManager.Instance.getThread(LoadFromFloderByFile, floder);
       }

       private static void LoadFromFolder(string floder)
       {
           IThreadManager.Instance.getThread(LoadFromFloderByThread,floder);
       }

       private static void LoadFromFloderByFile(object o)
       {
           object[] array = o as object[];
           string path = array[0].ToString();

           FileInfo f = new FileInfo(path);
           var str = File.ReadAllText(path);
            XmlDocument x = new XmlDocument();
            x.LoadXml(str);
            if (data.ContainsKey(f.Name))
            {
                data[f.Name] = x;
            }
            else
            {
                data.Add(f.Name, x);
            }
           EventLib.Instance.SendEvent(9005, null);
       }


       private static void LoadFromFloderByThread(object o)
       {
           object[] array = o as object[];
           string path = array[0].ToString();
           var dir = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories);
           foreach (var m in dir)
           {
              FileInfo f = new FileInfo(m);
              var str =  File.ReadAllText(m);
              XmlDocument x = new XmlDocument();
              x.LoadXml(str);
              if (data.ContainsKey(f.Name))
              {
                  data[f.Name] = x;
              }
              else
              {
                  data.Add(f.Name, x);
              }
           }
           EventLib.Instance.SendEvent(9005,null);
       }




    }

   public enum XMLType
   {
       Folder,
       File


   }
}
